package com.banmao.algorithm.No1To100.No24;

class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}

public class Solution1 {

    public ListNode swapPairs(ListNode head) {

        if(head == null) {
            return null;
        }
        if(head.next == null) {
            return head;
        }

        // 虚拟头节点
        ListNode dummy_head = new ListNode(-1, head);

        head = reverseBetween(dummy_head.next, dummy_head.next.next);
        return head;

    }

    private ListNode reverseBetween(ListNode left, ListNode right) {

        // 留存右边节点的下一个节点
        ListNode tempAfter = right.next;

        right.next = left;
        left.next = tempAfter;

        LinkedListUtils.printLinkedList(right);

        if(tempAfter != null && tempAfter.next != null) {
            left.next = reverseBetween(tempAfter, tempAfter.next);
        }

        return right;


    }

}
